<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-title">
        <h2>学生与班级管理系统</h2>
      </div>
      <!-- 登录/注册tab切换 -->
      <el-tabs v-model="activeTab" @tab-click="resetForm">
        <el-tab-pane label="登录" name="login">
          <el-form
            :model="loginForm"
            :rules="loginRules"
            ref="loginForm"
            class="login-form"
          >
            <el-form-item prop="userName">
              <el-input
                v-model="loginForm.userName"
                prefix-icon="el-icon-user"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                prefix-icon="el-icon-lock"
                type="password"
                show-password
                placeholder="请输入密码"
                @keyup.enter.native="handleLogin"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                @click="handleLogin"
                class="login-button"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-form
            :model="registerForm"
            :rules="registerRules"
            ref="registerForm"
            class="login-form"
          >
            <el-form-item prop="userName">
              <el-input
                v-model="registerForm.userName"
                prefix-icon="el-icon-user"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="registerForm.password"
                prefix-icon="el-icon-lock"
                type="password"
                show-password
                placeholder="请输入密码"
              ></el-input>
            </el-form-item>
            <el-form-item prop="confirmPassword">
              <el-input
                v-model="registerForm.confirmPassword"
                prefix-icon="el-icon-lock"
                type="password"
                show-password
                placeholder="请确认密码"
              ></el-input>
            </el-form-item>
            <el-form-item prop="role">
              <el-select v-model="registerForm.role" placeholder="请选择用户角色">
                <el-option label="管理员" value= "0"></el-option>
                <el-option label="教师" value= "1"></el-option>
                <el-option label="学生" value= "2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                :loading="loading"
                @click="handleRegister"
                class="login-button"
                >注册</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import http from '@/util/http';
import { mapActions } from 'vuex';

export default {
  name: "LoginPage",
  data() {
    // 确认密码的验证规则
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      activeTab: "login",
      loginForm: {
        userName: "",
        password: "",
        role: "",
      },
      registerForm: {
        userName: "",
        password: "",
        confirmPassword: "",
        role: "",
      },
      loginRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      registerRules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "用户名长度在3到20个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, message: "密码长度至少为6个字符", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请确认密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      },
      loading: false,
      registeredUsers: [], // 存储已注册用户
    };
  },
  methods: {
    ...mapActions('user', [
      'login',
      'logout'
    ]),
    ...mapActions('permission', [
      'generateRoutes',
      'resetRoutes'
    ]),
    // 重置表单
    resetForm() {
      if (this.activeTab === "login") {
        this.$nextTick(() => {
          this.$refs.loginForm && this.$refs.loginForm.resetFields();
        });
      } else {
        this.$nextTick(() => {
          this.$refs.registerForm && this.$refs.registerForm.resetFields();
        });
      }
    },
    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          // 使用http实例，不要拼接URL
          http.post("/user/login", {
            userName: this.loginForm.userName,
            password: this.loginForm.password
          })
          .then(response => {
            const data = response.data;
            this.loading = false;

            if (data.code === 200) {
              const userData = data.data;
              
              // 清除现有数据
              localStorage.removeItem('isLoggedIn');
              localStorage.removeItem('jwt_token');
              localStorage.removeItem('currentUser');
              localStorage.removeItem('permissionMenus');
              
              // 重置路由
              this.resetRoutes();
              
              // 保存新的登录数据
              localStorage.setItem('isLoggedIn', 'true');
              localStorage.setItem('jwt_token', userData.token);
              localStorage.setItem('currentUser', JSON.stringify(userData));
              
              // 如果后端没有直接返回菜单数据，则通过API获取
              if (!userData.menus || userData.menus.length === 0) {
                // 通过API获取菜单数据
                http.get("/menu/list/" + userData.role)
                  .then(menuResponse => {
                    const menuData = menuResponse.data;
                    if (menuData.code === 200) {
                      // 获取到菜单数据
                      const menus = menuData.data || [];
                      console.log('从API获取的菜单数据:', menus);
                      
                      // 保存到localStorage
                      localStorage.setItem('permissionMenus', JSON.stringify(menus));
                      
                      // 生成动态路由
                      this.handleRouteGeneration(menus, userData);
                    } else {
                      // 获取菜单失败，使用默认菜单
                      console.warn('获取菜单失败，使用默认菜单');
                      this.handleRouteGeneration([], userData);
                    }
                  })
                  .catch(err => {
                    console.error('获取菜单失败:', err);
                    // 获取失败，使用默认菜单
                    this.handleRouteGeneration([], userData);
                  });
              } else {
                // 使用后端返回的菜单
                const menus = userData.menus || [];
                console.log('后端直接返回的菜单数据:', menus);
                localStorage.setItem('permissionMenus', JSON.stringify(menus));
                
                // 生成动态路由
                this.handleRouteGeneration(menus, userData);
              }
            } else {
              this.$message.error(data.msg || "登录失败");
            }
          })
          .catch(error => {
            this.loading = false;
            console.error("登录请求错误:", error);
            this.$message.error("网络请求失败，请稍后再试");
          });
        } else {
          return false;
        }
      });
    },
    // 处理路由生成和跳转
    handleRouteGeneration(menus, userData) {
      this.generateRoutes(menus).then(() => {
        this.$message.success(`登录成功，欢迎 ${userData.userName}`);
        
        // 使用setTimeout确保路由注册完成后再跳转
        setTimeout(() => {
          // 根据是否有菜单决定跳转的路径
          if (menus && menus.length > 0) {
            // 确保路径格式正确
            const firstMenu = menus[0];
            const targetPath = firstMenu.path && firstMenu.path.startsWith('/') 
              ? firstMenu.path 
              : firstMenu.path 
                ? '/' + firstMenu.path 
                : '/statistics';
                
            console.log('登录成功，跳转到:', targetPath);
            this.$router.push(targetPath).catch(err => {
              console.warn('导航失败，尝试其他路径:', err);
              // 如果导航失败，尝试其他菜单或默认路径
              if (menus.length > 1) {
                const secondMenu = menus[1];
                const backupPath = secondMenu.path && secondMenu.path.startsWith('/') 
                  ? secondMenu.path 
                  : '/' + secondMenu.path;
                this.$router.push(backupPath).catch(() => {
                  // 如果仍然失败，使用根路径
                  this.$router.push('/');
                });
              } else {
                this.$router.push('/');
              }
            });
          } else {
            // 没有菜单数据，使用默认路径
            this.$router.push('/statistics');
          }
        }, 300);
      }).catch(error => {
        console.error('生成路由失败:', error);
        this.$message.error('加载菜单失败，请稍后再试');
        this.$router.push('/statistics');
      });
    },
    // 注册
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          http.post(this.httpUrl + "/user/register", {
              userName: this.registerForm.userName,
              password: this.registerForm.password,
              role: this.registerForm.role,
            })
            .then((res) => {
              this.loading = false;
              const data = res.data;

              if (data.code === 200) {
                // 注册成功
                this.$message.success('注册成功，请登录');

                // 切换到登录标签
                this.activeTab = 'login';
              } else {
                this.$message.error(data.msg || "注册失败");
              }
            })
            .catch((err) => {
              this.loading = false;
              console.error("登录请求错误:", err);
              this.$message.error("网络请求失败，请稍后再试");
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #409eff 0%, #1e88e5 100%);
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  margin-top: 10px;
}

.login-tips {
  margin-top: 15px;
  font-size: 12px;
  color: #999;
  text-align: center;
}

/* 自定义tab样式 */
::v-deep .el-tabs__header {
  margin-bottom: 25px;
}

::v-deep .el-tabs__item {
  font-size: 16px;
  padding: 0 20px;
}
</style>
